/**
 * Created with IntelliJ IDEA.
 * User: ajhin
 * Date: 2/17/14
 * Time: 9:53 AM
 * To change this template use File | Settings | File Templates.
 */
package com.societyGames.utility
{
import com.greensock.TweenNano;
import com.greensock.easing.Linear;

import flash.display.DisplayObject;

/***
 * Makes a display object bounce.
 */
public class Bouncer
{
  private var _displayObject:DisplayObject;
  private var _bounceBottom:Number;
  private var _halfBounceTime:Number;
  private var _bounceTop:Number;
  private var _tweenNano:TweenNano;

  public function Bouncer(displayObject:DisplayObject)
  {
    if (displayObject == null)
    {
      throw new ArgumentError("Argument displayObject cannot be null.");
    }
    _displayObject = displayObject;
  }

  public function set bounceTop(value:Number):void
  {
    _bounceTop = value;
  }

  public function set bounceBottom(value:Number):void
  {
    _bounceBottom = value;
  }

  public function set bounceTime(value:Number):void
  {
    _halfBounceTime = value * 0.5;
  }

  public function bounce(delayTimeSeconds:Number = 0):void
  {
    stop();
    _tweenNano = TweenNano.to(_displayObject, _halfBounceTime,
            {
              y: _bounceTop,
              ease: Linear.easeOut,
              delay: delayTimeSeconds,
              onComplete: onBounceUpComplete
            });
  }

  public function stop():void
  {
    if (_tweenNano != null)
    {
      var tempTweenNano:TweenNano = _tweenNano;
      _tweenNano = null;
      tempTweenNano.complete();
      _displayObject.y = _bounceBottom;
    }
  }

  private function onBounceUpComplete():void
  {
    if (_tweenNano != null)
    {
      _tweenNano = TweenNano.to(_displayObject, _halfBounceTime,
              {y: _bounceBottom,
                ease: Linear.easeIn,
                onComplete: onBounceDownComplete});
    }
  }

  private function onBounceDownComplete():void
  {
    _tweenNano = null;
  }
}
}
